define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'adminlte', 'template'], function ($, undefined, Backend, Table, Form, Adminlte, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'dormitory/dorm/index',
                    add_url: 'dormitory/dorm/add',
                    edit_url: 'dormitory/dorm/edit',
                    del_url: 'dormitory/dorm/del',
                    multi_url: 'dormitory/dorm/multi',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [

                        {field: 'state', checkbox: true, },
                        //通过Ajax渲染searchList，也可以使用JSON数据
                        // {
                        //     field: 'building_number', title: __('Building'), searchList: function (column) {
                        //         return Template('gardenTpl', {});
                        //     }, formatter: function (value, row, index) {
                        //         return '无';
                        //     }, visible: false
                        // },
                        {field: 'number', title: __('Number'), operate: "LIKE %...%",},
                        {field: 'name', title: __('Name'), operate: false},
                        // {field: 'garden_name', title: __('Garden Name'), operate: false},
                        // {field: 'building_name', title: __('Building Name'), operate: false},
                        {field: 'floor', title: __('Floor'), operate: false, formatter: Controller.api.formatter.floor},
                        {field: 'bed_count', title: __('Capacity'), operate: false, formatter: Controller.api.formatter.capacity},
                        {field: 'type_text', title: __('Type'), operate: false},
                        {field: 'category_text', title: __('Category'), operate: false},
                        {field: 'status', title: __('是否显示'), align: 'center', formatter: Table.api.formatter.toggle, operate: false},
                        // {field: 'status', title: __('是否显示'), visible: false, searchList: {1: __('是'), 2: __('否')}},
                        {field: 'qrcode', title: __('二维码'), operate: false, formatter: Controller.api.formatter.qrcode},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                commonSearch: true,
                searchFormVisible: true,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 监听下拉列表改变的事件
            $(document).on('change', 'select[name=garden_number]', function () {
                $("#garden_number").val($(this).val());
            });

            // 生成床位号
            $(document).on("click", ".btn-initBed", function () {
                //在table外不可以使用添加.btn-change的方法
                //只能自己调用Table.api.multi实现
                //如果操作全部则ids可以置为空
                var ids = Table.api.selectedids(table);
                Table.api.multi("changestatus", ids.join(","), table, this);
            });

            // 二维码
            $(document).on("click", ".btn-qrCode", function () {
                Backend.api.open('dormitory/dorm/qrcode', '二维码', {area:['50%','60%']});
            });
            $(document).delegate( ".qrcode", "click",function () {
                Backend.api.open('', '二维码', {
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    area: '516px',
                    skin: 'layui-layer-nobg', //没有背景色
                    shadeClose: true,
                    content: $('#qrcode_'+$(this).data('id'))
                });
            });

        },
        add: function () {

            // 学校改变时 拉取园区列表
            $(document).delegate('.school', 'change', function () {
                $.ajax({
                    url: "common/gardens",
                    type: 'post',
                    dataType: 'json',
                    data: {school_id: $(this).val()},
                    success: function (ret) {
                        if (ret.code === 1) {
                            $('.garden').html(Template('tpl', ret));
                        } else {
                            Backend.api.toastr.error(ret.msg);
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });

            });
            // 园区改变时 拉取楼栋列表
            $(document).delegate('.garden', 'change', function () {
                $.ajax({
                    url: "common/buildings",
                    type: 'post',
                    dataType: 'json',
                    data: {garden_id: $(this).find("option:selected").data("id")},
                    success: function (ret) {
                        if (ret.code === 1) {
                            $('.building').html(Template('tpl', ret));
                        } else {
                            Backend.api.toastr.error(ret.msg);
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });

            });

            // 楼栋
            $(document).delegate('.building', 'change', function () {

                var building_id = $(this).find("option:selected").data("id");

                if (building_id > 0) {
                    $.ajax({
                        url: "common/floorCount",
                        type: 'post',
                        dataType: 'json',
                        data: {building_id: building_id},
                        success: function (ret) {
                            if (ret.code === 1) {
                                $('.floor').html(Template('floorTpl', ret.data));
                                $('#c-bed-count').val(ret.data.dorm_bed_count);
                                $('#c-price').val(ret.data.dorm_price);
                            } else {
                                Backend.api.toastr.error(ret.msg);
                            }
                        }, error: function (e) {
                            Backend.api.toastr.error(e.message);
                        }
                    });
                }

            });

            $(document).delegate('.floor', 'change', function () {

                var garden_number = $(".garden").val();
                var $building = $('.building');
                $.ajax({
                    url: "dormitory/dorm/floorMaxDorm",
                    type: 'post',
                    dataType: 'json',
                    data: {garden_number:garden_number,building_number:$building.val(), floor: $(this).val()},
                    success: function (ret) {
                        if (ret.code === 1) {
                            var num = ret.data.num;
                            $('.num').val(num);
                            var number = $building.val();
                            $('#c-number').val(number + '-' + num);
                            var name = $building.find('option:selected').text();
                            $('#c-name').val(name + '-' + num);

                        } else {
                            Backend.api.toastr.error(ret.msg);
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });
            });

            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        qrcode: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'dormitory/dorm/index?qrcode=1',
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                }
            });

            var table = $("#table");

            Template.helper("Moment", Moment);

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                templateView: true,
                columns: [
                    [
                        {field: 'garden_name', title: '园区', operate: false},
                        {field: 'building_name', title: __('楼栋'), operate: false},
                        {field: 'name', title: __('寝室'), operate: false},
                        {field: 'url', title: __('图片'), operate: false},
                    ],
                ],
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                //分页大小
                pageSize: 12,
                showToggle: false,
                showColumns: false,
                showExport: false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        ranking: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    ranking_url: 'dormitory/dorm/ranking',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.ranking_url,
                sortName: 'total_score',
                columns: [
                    [
                        {field: 'num', title: __('序号'), operate: false},
                        {field: 'sort', title: __('排名'), operate: false},
                        {field: 'school_name', title: __('学校'), operate: false},
                        {field: 'garden_name', title: __('园区'), operate: false},
                        {field: 'building_name', title: __('楼栋'), operate: false},
                        {field: 'floor', title: __('所在楼层'), operate: false},
                        {field: 'number', title: __('寝室编号'), operate: false},
                        {field: 'bed_used_count', title: __('寝室人数'), operate: false},
                        {field: 'score', title: __('宿舍积分'), operate: false},
                        {field: 'total_score', title: __('总积分'), operate: false},
                    ]
                ],
                //禁用默认搜索
                search: true,
                //启用普通表单搜索
                commonSearch: true,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: true,
                //分页大小
                pageSize: 12

            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        record: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    record_url: 'dormitory/dorm/record',
                    del_url: 'dormitory/dorm/delRecord',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.record_url + '?dorm_id=' + Config.dorm_id,
                sortName: 'id',
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'score', title: __('点评分数'), operate: false},
                        {field: 'behavior_name', title: __('点评行为'), operate: false},
                        {
                            field: 'created_at',
                            title: __('点评时间'),
                            sortable: true,
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange'
                        },
                        {field: 'record_user_group', title: __('点评人'), operate: false},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }

                    ]
                ],
                //禁用默认搜索
                search: true,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: true,
                //分页大小
                pageSize: 12

            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            //当内容渲染完成后
            table.on('post-body.bs.table', function (e, settings, json, xhr) {

                //点击切换/排序/删除操作后刷新左侧菜单
                $(".btn-change[data-id],.btn-delone,.btn-dragsort").data("success", function (data, ret) {
                    Controller.api.refreshtable();
                    return false;
                });

            });
            //批量删除后的回调
            $(".toolbar > .btn-del,.toolbar .btn-more~ul>li>a").data("success", function (e) {
                Controller.api.refreshtable();
            });

        },
        api: {
            formatter: {
                floor: function (value, row, index) {
                    return value + __('Floor Tips');
                },
                capacity: function (value, row, index) {
                    return row.bed_used_count + '/' + value;
                },
                qrcode: function (value, row, index) {
                    return "<img id='qrcode_"+row.id+"' style='width:100%;display:none;' src='" + row.qrcode + "'><a class='qrcode' href='javascript:;' style='max-width: 50px; max-height: 50px; display:inline-block;' data-id='" + row.id + "'><img style='width:100%;' src='" + row.qrcode + "'></a>";
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});